<template>
  <!-- 申请付款的页面 -->
  <div class="paymentDialogContainer">
    <el-drawer
      :title="
        operateType === 'add'
          ? '申请付款'
          : operateType === 'edit'
          ? '编辑付款'
          : '付款详情'
      "
      :before-close="handleClose"
      :visible.sync="dialogVisible"
      direction="rtl"
      custom-class="demo-drawer"
      :wrapperClosable="false"
      @open="beforeOpenDrawer"
      ref="drawer"
      size="40%"
    >
      <div class="demo-drawer__content">
        <el-form
          label-position="right"
          :model="formData"
          :rules="rules"
          ref="formName"
        >
          <div class="formTitle">基本信息</div>
          <el-form-item
            class="formItemWidth"
            label="承运商名称："
            :label-width="formLabelWidth"
            prop="carrier_name"
          >
            <span>{{ carrier_name || carrier_name_receive }}</span>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="申请付款原因："
            prop="apply_payment_reason"
            label-width="145px"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="请输入申请付款原因"
              type="textarea"
              v-model="formData.apply_payment_reason"
            ></el-input>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="发票附件："
            prop="invoice_attachment"
            label-width="145px"
          >
            <el-upload
              :disabled="operateType === 'info'"
              class="upload-demo"
              action
              :auto-upload="false"
              :on-preview="handlePreview"
              :on-remove="handleRemoveAttachment"
              :before-remove="beforeRemoveAttachment"
              :on-change="handleChangeAttachment"
              multiple
              :file-list="fileList"
              list-type="picture"
            >
              <el-button plain size="small" type="primary" icon="el-icon-upload"
                >上传文件</el-button
              >
              <!-- <span slot="tip" class="el-upload__tip" style="margin-left: 20px"
                >支持扩展名：</span
              > -->
            </el-upload>
            <el-dialog :visible.sync="dialogImageVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="发票类型："
            :label-width="formLabelWidth"
            prop="invoice_type"
          >
            <el-select
              :disabled="operateType === 'info'"
              clearable
              style="width: 100%"
              placeholder="请选择发票类型"
              v-model="formData.invoice_type"
            >
              <el-option label="专用发票" value="0"></el-option>
              <el-option label="普通发票" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            :required="formData.rate === '9'"
            class="formItemWidth"
            label="发票金额："
            :label-width="formLabelWidth"
            prop="invoice_amount"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="请输入发票金额（含税）"
              v-model="formData.invoice_amount"
              ><template slot="append">元</template></el-input
            >
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="发票税率："
            style="width: 700px"
            prop="invoice_rate"
            :label-width="formLabelWidth"
          >
            <el-radio-group
              v-model="formData.invoice_rate"
              :disabled="operateType === 'info'"
            >
              <el-radio label="3">3%</el-radio>
              <el-radio label="6">6%</el-radio>
              <el-radio label="9">9%</el-radio>
              <el-radio label="13">13%</el-radio>
              <el-radio :label="rate"
                >其它，
                <el-input
                  style="width: 55px"
                  :disabled="operateType === 'info'"
                  v-model="rate"
                  oninput="value=value.replace(/[^0-9.]/g,'')"
                ></el-input
                >%
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="formTitle">付款信息</div>
          <el-form-item
            class="formItemWidth"
            label="承运商发票主体："
            :label-width="formLabelWidth"
            prop="carrier_invoice_body.invoice_body_name"
            required
          >
            <el-select
              :disabled="operateType === 'info'"
              allow-create
              filterable
              clearable
              @clear="
                formData.carrier_invoice_body.invoice_body_name = '';
                formData.carrier_invoice_body.invoice_body_id = 0;
                company_invoice_book_list = invoiceBookList;
              "
              reserve-keyword
              style="width: 100%"
              placeholder="请选择承运商发票主体"
              @change="selectInvoiceCustomer"
              v-model="formData.carrier_invoice_body.invoice_body_name"
            >
              <el-option
                v-for="item in customer_invoice_book_list"
                :key="item.id"
                :label="item.invoice_body_name"
                :value="item.invoice_body_name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="纳税人识别号："
            :label-width="formLabelWidth"
            prop="carrier_invoice_body.taxpayer_identify_number"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="请输入纳税人识别号"
              v-model="formData.carrier_invoice_body.taxpayer_identify_number"
            ></el-input>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="公司地址："
            :label-width="formLabelWidth"
            prop="carrier_invoice_body.company_address"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="请输入公司地址"
              v-model="formData.carrier_invoice_body.company_address"
            ></el-input>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="公司电话："
            :label-width="formLabelWidth"
            prop="carrier_invoice_body.company_phone"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="请输入公司电话"
              v-model="formData.carrier_invoice_body.company_phone"
            ></el-input>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="开户行："
            :label-width="formLabelWidth"
            prop="carrier_invoice_body.bank_of_deposit"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="请输入开户行"
              v-model="formData.carrier_invoice_body.bank_of_deposit"
            ></el-input>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="开户行账号："
            :label-width="formLabelWidth"
            prop="carrier_invoice_body.account_no"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="请输入开户行账号"
              v-model="formData.carrier_invoice_body.account_no"
            ></el-input>
          </el-form-item>

          <el-form-item
            class="formItemWidth"
            label="收款人姓名:"
            :label-width="formLabelWidth"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="请输入收款人姓名"
              v-model="formData.payee"
            ></el-input>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="收款银行:"
            :label-width="formLabelWidth"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="请输入收款银行"
              v-model="formData.receive_bank"
            ></el-input>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="收款银行账号:"
            :label-width="formLabelWidth"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="收款银行账号"
              v-model="formData.receive_bank_no"
            ></el-input>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="付款金额："
            :label-width="formLabelWidth"
            required
            prop="payment_amount"
          >
            <el-input disabled v-model="formData.payment_amount"
              ><template slot="append">元</template></el-input
            >
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="付款方式："
            :label-width="formLabelWidth"
            prop="payment_method"
          >
            <el-select
              :disabled="operateType === 'info'"
              clearable
              style="width: 100%"
              placeholder="请选择付款方式"
              v-model="formData.payment_method"
            >
              <el-option
                v-for="item in revenue_type_list"
                :key="item.item_code"
                :label="item.item_name"
                :value="item.item_code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="预计付款时间："
            :label-width="formLabelWidth"
            prop="payment_time"
          >
            <el-date-picker
              :disabled="operateType === 'info'"
              v-model="formData.payment_time"
              type="datetime"
              align="right"
              value-format="timestamp"
              unlink-panels
              :picker-options="pickerOptions"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="成本类型："
            :label-width="formLabelWidth"
            prop="cost_type"
          >
            <el-input disabled v-model="formData.cost_type"></el-input>
          </el-form-item>
          <!-- 我方发票主体是选择了开票名称主体之后带出来的，输入的情况就用api请求 -->
          <el-form-item
            class="formItemWidth"
            label="我方发票主体："
            :label-width="formLabelWidth"
            prop="company_invoice_body_id"
          >
            <el-select
              style="width: 100%"
              v-if="formData.carrier_invoice_body.invoice_body_id !== 0"
              disabled
              @change="selectCompanyInvoiceBook"
              v-model="formData.company_invoice_body_id"
            >
              <el-option
                v-for="item in company_invoice_book_list"
                :key="item.relation_invoice_body_id"
                :label="item.relation_invoice_body_name"
                :value="item.relation_invoice_body_id"
              ></el-option>
            </el-select>
            <el-select
              v-else
              style="width: 100%"
              :disabled="operateType === 'info'"
              @change="selectCompanyInvoiceBook"
              v-model="formData.company_invoice_body_id"
            >
              <el-option
                v-for="item in company_invoice_book_list"
                :key="item.id"
                :label="item.invoice_body_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button
            v-show="operateType !== 'info'"
            type="primary"
            @click="submitForm('formName')"
            :loading="loading"
            >{{ operateType === "add" ? "发起审核" : "保存" }}</el-button
          >
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { timestamp10 } from "@/utils/mUtils";
import { dictionaryBatch } from "@/api/waybill";
import {
  reqApplyForPayment, //新增付款
  reqEditPayment, //编辑付款
  reqPaymentInfo, //付款详情
  reqReceiptBookList,
} from "@/api/finance";
import { uploading } from "@/page/material/common/common";
export default {
  name: "paymentDialog",
  props: ["account_id", "carrier_id", "carrier_name", "now_price"],
  data() {
    return {
      operateType: "", //操作类型
      dialogVisible: false,
      loading: false,
      account_no_receive: "",
      carrier_name_receive: "",
      invoiceBookList: [], //请求到的列表
      customer_invoice_book_list: [], //发票簿的下拉列表
      company_invoice_book_list: [], //我方发票主体的列表
      formData: {
        account_id: "", // 对账单id
        carrier_id: "", // 承运商id
        apply_payment_reason: "", // 申请付款原因
        invoice_attachment: [], // 发票附件
        invoice_type: "", //  发票类型：0专用，1普通
        invoice_amount: "", // 发票金额
        invoice_rate: 0, //  发票税率
        company_invoice_body_id: "", //应付方发票主体
        carrier_invoice_body: {
          invoice_body_id: 0, // 发票主体id
          invoice_body_name: "", // 发票主体名
          taxpayer_identify_number: "", // 纳税人识别号
          company_address: "", // 公司地址
          company_phone: "", // 公司电话
          bank_of_deposit: "", // 开户行
          account_no: "", // 开户行账号
        }, //收款方(承运商)发票主体
        payment_method: "", //  付款方式：0现金，1银行卡，2支票，3电汇，5汇款，6贷记，7其他
        payment_amount: "", //付款金额
        payment_time: "", // 付款截止时间
        cost_type: "运输成本", // 成本类型
        payee: "", //收款人
        receive_bank: "", //收款银行
        receive_bank_no: "", //收款银行账号
      },
      rate: "", //其他税率
      fileList: [], //上传的附件
      dialogImageVisible: false, //附件预览
      dialogImageUrl: "", //预览的图片路径
      revenue_type_list: [], //收支方式列表
      rules: {
        // invoice_attachment: [
        //   { required: true, message: "请输入活动名称", trigger: "blur" },
        //   { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        // ],
        invoice_attachment: [
          { required: true, message: "请上传发票附件", trigger: "blur" },
        ],
        "carrier_invoice_body.invoice_body_name": [
          {
            required: true,
            message: "请选择或输入承运商发票主体",
            trigger: "change",
          },
        ],
        "carrier_invoice_body.taxpayer_identify_number": [
          { required: true, message: "请输入纳税人识别号", trigger: "blur" },
        ],
        "carrier_invoice_body.company_address": [
          { required: true, message: "请输入公司地址", trigger: "blur" },
        ],
        "carrier_invoice_body.company_phone": [
          { required: true, message: "请输入公司电话", trigger: "blur" },
        ],
        "carrier_invoice_body.bank_of_deposit": [
          { required: true, message: "请输入开户行", trigger: "blur" },
        ],
        "carrier_invoice_body.account_no": [
          { required: true, message: "请输入开户行账号", trigger: "blur" },
        ],
        payment_method: [
          { required: true, message: "请选择付款方式", trigger: "change" },
        ],
        invoice_type: [
          { required: true, message: "请选择发票类型", trigger: "change" },
        ],
        invoice_amount: [
          { required: true, message: "请输入发票金额", trigger: "blur" },
          {
            pattern:
              /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: "请输入正确格式,可保留两位小数",
          },
        ],
        invoice_rate: [
          { required: true, message: "请选择发票税率", trigger: "change" },
        ],
        payment_time: [
          { required: true, message: "请输入预计付款时间", trigger: "change" },
        ],
        company_invoice_body_id: [
          { required: true, message: "请选择我方发票主体", trigger: "change" },
        ],
      },
      formLabelWidth: "145px",
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      timer: null,
    };
  },
  watch: {
    "formData.invoice_amount"(val) {
      this.formData.payment_amount = val;
    },
  },
  methods: {
    async beforeOpenDrawer() {
      this.$nextTick(async () => {
        this.operateType = this.$store.getters.operateType;
        let result2 = await dictionaryBatch({
          codes: ["revenue_type"], //请求财务管理收支方式
        });
        if (result2.code === 10000) {
          this.revenue_type_list = result2.data.list.revenue_type.reverse();
        }

        let result3 = await reqReceiptBookList({
          body_belong: "0", //请求我方发票主体公司
        });
        if (result3.code === 10000) {
          this.invoiceBookList = result3.data;
          this.company_invoice_book_list = result3.data;
        }
        this.formData.invoice_amount = this.now_price;

        if (this.operateType === "edit" || this.operateType === "info") {
          let result = await reqPaymentInfo({
            account_id: this.account_id * 1,
          });
          if (result.code === 10000 && result.data !== null) {
            this.formData = result.data;
            this.company_invoice_book_list = [
              {
                relation_invoice_body_id:
                  result.data.company_invoice_body.invoice_body_id,
                relation_invoice_body_name:
                  result.data.company_invoice_body.invoice_body_name,
              },
            ];
            this.formData.payment_time = this.formData.payment_time * 1000;
            this.fileList = result.data.invoice_attachment.map((url) => {
              return url;
            });
            this.rate = result.data.invoice_rate;
            this.carrier_name_receive = result.data.carrier_name;
            this.formData.account_id = result.data.account_id * 1;
            this.formData.carrier_id = result.data.carrier_id * 1;
            this.formData.company_invoice_body_id =
              result.data.company_invoice_body.invoice_body_id * 1;
          }
          // console.log('this.operateType === "edit"');
        }

        let result1 = await reqReceiptBookList({
          body_belong: "2", //请求发票主体客户下拉用这个
          belong_to_id: this.carrier_id * 1, //对账单上的客户id
          invoice_body_name: "", //发票主体名
        });
        if (result1.code === 10000) {
          this.customer_invoice_book_list = result1.data;
        }
      });
    },
    async selectInvoiceCustomer(val) {
      const { carrier_invoice_body } = this.formData;
      let piece = this.customer_invoice_book_list.find(
        (item) => item.invoice_body_name === val
      );
      if (piece) {
        carrier_invoice_body.invoice_body_id = piece.id;
        // this.company_invoice_book_list = this.customer_invoice_book_list; //如果选择了客户发票主体,那就直接带出piece里面的公司主体
        this.formData.carrier_invoice_body.invoice_body_id = piece.id;
        carrier_invoice_body.invoice_body_name = piece.invoice_body_name;
        carrier_invoice_body.taxpayer_identify_number =
          piece.taxpayer_identify_number;
        carrier_invoice_body.company_address = piece.company_address;
        carrier_invoice_body.company_phone = piece.company_phone;
        carrier_invoice_body.bank_of_deposit = piece.bank_of_deposit;
        carrier_invoice_body.account_no = piece.account_no;
        this.company_invoice_book_list = [
          {
            relation_invoice_body_id: piece.relation_invoice_body_id,
            relation_invoice_body_name: piece.relation_invoice_body_name,
          },
        ];
        this.formData.company_invoice_body_id = piece.relation_invoice_body_id;
      } else {
        carrier_invoice_body.invoice_body_id = 0;
      }
    },
    selectCompanyInvoiceBook() {
      this.$forceUpdate();
      // if (
      //   this.formData.customer_invoice_book_info.invoice_body_id * 1 !==
      //   NaN
      // ) {
      //   this.formData.customer_invoice_book_info.invoice_body_name =
      //     this.formData.customer_invoice_book_info.invoice_body_id;
      //   this.formData.customer_invoice_book_info.invoice_body_id = "";
      // }
    },
    selectCategory(val) {
      //看看动态表单验证升不生效
      if (val === "0") {
        this.formData.rate = "9";
      } else {
        this.formData.rate = "6";
      }
    },
    //上传附件的函数
    beforeRemoveAttachment(file, fileList) {
      return this.$confirm("是否删除该附件");
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogImageVisible = true;
    },
    handleRemoveAttachment(file, fileList) {
      const index = this.fileList.findIndex(
        (item, index) => item.uid === file.uid
      ); //找到被删除的id
      // console.log(index);
      if (index > -1) {
        this.formData.invoice_attachment.splice(index, 1);
        this.fileList.splice(index, 1);
      }
    },
    handleChangeAttachment(file, fileList, type) {
      this.fileList = fileList;
      var filelist = file.raw; //文件
      var filename = file.raw.uid + file.raw.name; //通过 uid和name组成文件的名字
      uploading(filelist, filename, type).then((res) => {
        // this.formData.invoice_attachment.push(res.res.requestUrls[0]);
        this.formData.invoice_attachment.push({
          uid: file.uid,
          url: res.res.requestUrls[0],
        });
      });
    },

    handleClose() {
      this.dialogVisible = false;
      // this.$refs.formName.resetFields();
    },
    submitForm(formName) {
      //提交验证表单
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          //在这里写提交
          let result;
          this.formData.account_id = this.account_id * 1;
          this.formData.carrier_id = this.carrier_id * 1;
          if (this.$parent.selectedDetails[0].ar_status == 0) {
            this.formData.payment_time =
              timestamp10(this.formData.payment_time) * 1;
            result = await reqApplyForPayment(this.formData);
          } else {
            if (this.formData.remark !== "") {
              this.$message({
                message: this.formData.remark,
                type: "error",
              });
              return;
            }
            delete this.formData.status;
            this.formData.payment_time =
              timestamp10(this.formData.payment_time) * 1;
            result = await reqEditPayment(this.formData);
          }
          if (result.code === 10000) {
            this.$message({
              message: "保存成功",
              type: "success",
            });
            this.dialogVisible = false;
            this.$parent.displayOrders();
            // this.$refs[formName].resetFields();
            // Object.assign(this.$data, this.$options.data());
          }
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },
    cancelForm() {
      this.dialogVisible = false;
      // this.$refs.formName.resetFields();
      clearTimeout(this.timer);
    },
  },
};
</script>

<style scoped lang="less">
.paymentDialogContainer {
  .demo-drawer__content {
    margin-top: -20px;
    .formItemWidth {
      width: 500px;
    }
    .formTitle {
      margin: 20px 25px;
      font-weight: bold;
    }
    .demo-drawer__footer {
      width: 100%;
      display: flex;
      justify-content: center;
      padding-bottom: 10px;
    }
    .el-radio {
      margin-right: 10px;
    }
  }
}
</style>